package com.dis.common.interceptor;

import cn.hutool.core.util.StrUtil;
import com.dis.common.context.BaseContext;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


// 拦截器，要注册到mvc
// 解析网关过滤器的用户信息，或者OpenFeign拦截器
public class UserInfoInterceptor implements HandlerInterceptor {
    @Override //preHandle请求之前执行
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1.从网关请求头里获取用户的登录信息
        String userInfo = request.getHeader("user-info");
        // 2.判断是否获得了用户，如果有，存到ThreadLocal
        if(StrUtil.isNotBlank(userInfo)){
            BaseContext.setCurrentId(Long.valueOf(userInfo));
        }
        // 放行
        return true;
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
       // 清理用户信息
       BaseContext.removeCurrentId();
    }
}
